/**
 * jims
 */
package com.jims.master.modules.sync.service;

import com.jims.master.common.persistence.BaseEntity;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.sync.dao.*;
import com.jims.master.modules.sync.entity.*;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.dao.SysOrgDictDao;
import com.jims.master.modules.sys.entity.SysOrgDict;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DeptUtils;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 检验申请Service
 * @author 陈晓阳
 * @version 2017-03-16
 */
@Service
@Transactional(readOnly = true)
public class LabApplyService extends CrudService<LabApplyDao, LabApply> {

    @Autowired
    private LabItemDao labItemDao;
    @Autowired
    private ExamApplyService examApplyService;
    @Autowired
    private ClinicItemDictDao clinicItemDictDao;
    @Autowired
    private LabItemService labItemService;
    @Autowired
    private LabApplyDao labApplyDao;
    @Autowired
    private PatVisitService patVisitService;

    @Autowired
    private ClinicVsChargeDao clinicVsChargeDao;
    @Autowired
    private ClinicMasterService clinicMasterService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private OrgDeptDao orgDeptDao;
    @Autowired
    private PriceListDao            priceListDao;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
    private LabVsClinicDao labVsClinicDao;
    @Autowired
    private SysOrgDictDao sysOrgDictDao;
    @Autowired
    private LabConsumablService labConsumablService;



    public LabApply get(String id) {
        return super.get(id);
    }

    public List<LabApply> findList(LabApply labApply) {
        return super.findList(labApply);
    }

    public Page<LabApply> findPage(Page<LabApply> page, LabApply labApply) {
        return super.findPage(page, labApply);
    }

    @Transactional(readOnly = false)
    public int save(LabApply labApply) {
        return super.save(labApply);
    }

    @Transactional(readOnly = false)
    public int delete(LabApply labApply) {
        return super.delete(labApply);
    }

    /**
     * 查询此个病人的所有待做和未做的检验项目
     *
     * @param labItemPage
     * @param labItem
     * @return
     * @author jict
     */
    public Page<LabItem> queryLabByPatient(Page<LabItem> labItemPage, LabItem labItem) {
        labItem.updateOrgId();
        labItem.setPage(labItemPage);
        List<LabItem> lbsItems = this.labItemDao.queryExamByPatient(labItem.getLabApply().getPatientId(), UserUtils.getOrgId(), labItem.getItemName());
        labItemPage.setList(lbsItems);
        return labItemPage;
    }

    /**
     * 检验申请保存
     * @return
     * @author jict
     * @update by lijl 2018/01/26 增加门诊住院标识
     */

    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public int saveLabApplyData(LabApply labApply,String clincItemIds,String type,String num) {
        //1 保存检验申请主表与检验申请明细
        LabApply labApply1 = saveLabApply(labApply);
        //2 保存子表
        int result = this.saveLabItems(labApply,clincItemIds);//多条记录 对应诊疗项目
        //3保存耗材
        LabConsumabl labConsumabl = new LabConsumabl();
        if (!type.equals("0")){
            //0:不需要采血，1：需要
            labConsumabl.setBloodFlag("1");
            //0：不需要采血，1：小孩 2：大人
            labConsumabl.setType(type);
        }else{
            labConsumabl.setType("0");
            labConsumabl.setBloodFlag("0");
        }
        labConsumabl.setNum(num);
        labConsumabl.setBloodVessel("4133c1c357ec40189ed9a60f15f28d74");
        labConsumabl.setLabapply(labApply.getId());
        int i = labConsumablService.save(labConsumabl);
        return result;
    }

    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public int saveLabApplyDatas(LabApply labApply,String clincItemIds,String type,String num) {
        //1 保存检验申请主表与检验申请明细
        LabApply labApply1 = saveLabApply(labApply);
        //2 保存子表
        int result = this.saveLabItem(labApply,clincItemIds);//多条记录 对应诊疗项目
        return result;
    }

    /**
     * @param tubeId
     * @return void
     * @throws
     * @Title: saveLabTube
     * @Description: （保存管费以及采血费等）
     * @author zhangyao
     * @date 2017/12/1 0001
     * @update by lijl 2018/01/26 增加门诊住院标识
     */
    private Boolean saveLabTube(String tubeId, Boolean isCost, LabItem labItem,String outpOrInp) {
        List<ClinicItemDict> listp = null;
        User user = UserUtils.getUser();
        SysOrgDict orgDict = sysOrgDictDao.get(tubeId);
        if (!isCost) {
            if ("1".equals(orgDict.getValue())) {
                isCost = true;
            }
        }
        //获取对照项目
        listp = clinicItemDictDao.findClinicItemByDictId(tubeId, user.getOrgId(),outpOrInp);
        if(listp.size()>0){
            for (int i = 0; i <listp.size() ; i++) {
                //组织需要保存数据
                List<SaveDataVo> resultVal=organizeItems(listp.get(i),labItem);
               // this.examApplyService.commonSave(resultVal);
            }
        }
        return isCost;
    }


    /**
     * @Title: organizeItems
     * @Description: （组织材料管数据）
     * @param
     * @param labItem
     * @return java.util.List<com.jims.master.modules.doctor.vo.SaveDataVo>
     * @author zhangyao
     * @date 2017/12/1 0001
     * @throws
     */
    private List<SaveDataVo> organizeItems(ClinicItemDict clinicItemDict,LabItem labItem) {
        List<SaveDataVo> resultVal = new ArrayList<SaveDataVo>();
        Double price = this.clinicItemDictDao.findPriceById(clinicItemDict.getId());
        SaveDataVo saveDataVo = new SaveDataVo();
        saveDataVo.setPatientId(labItem.getLabApply().getPatientId());
        saveDataVo.setItemName(clinicItemDict.getItemName());
        saveDataVo.setImplementDept(labItem.getLabApply().getImplementDept());
        saveDataVo.setChargeFlag(labItem.getLabApply().getChargeFlag());
        saveDataVo.setConfirmFlag(labItem.getLabApply().getConfirmFlag());
        saveDataVo.setClinicId(labItem.getLabApply().getClinicId());
        saveDataVo.setApplyDept(labItem.getLabApply().getBillingDept());
        saveDataVo.setNum(1);
        saveDataVo.setClinicItemId(clinicItemDict.getId());
        saveDataVo.setApplyId(null);
        saveDataVo.setSumPrice(price != null ? price : 0);
        saveDataVo.setItemClass(clinicItemDict.getItemClass());
        saveDataVo.setIsApply(labItem.getLabApply().getId());
        saveDataVo.setApplyNo(labItem.getLabApply().getApplyOn());
        saveDataVo.setRcptNo("");//收费号
        saveDataVo.setImplementUser("");//执行人
        saveDataVo.setInoroutFlag("0");
        resultVal.add(saveDataVo);
    return resultVal;

}

    private int saveLabItems(LabApply labApply,String clincItemId) {
        String[] clincItemIds = clincItemId.split(",");
        for (String clinicItemId : clincItemIds) {
            String[] itemType = clinicItemId.split("-");
            ClinicItemDict clinicItemDict = this.clinicItemDictDao.get(itemType[0]);
            LabItem saveData = new LabItem();
            saveData.setApplyId(labApply.getId());
            saveData.setItemType(itemType[1]);
            saveData.setItemName(clinicItemDict.getItemName());
            saveData.setItemCode(clinicItemDict.getItemCode());
            saveData.setClinicItemId(clinicItemDict.getId());
            logger.debug(saveData.getItemType());
            Double price = this.clinicItemDictDao.findPriceById(clinicItemDict.getId());
            saveData.setCosts((price!=null?price:0) + "");
            saveData.setOrgId(labApply.getOrgId());
            this.labItemService.save(saveData);
        }
        return clincItemIds.length;
    }

    /**
     * 检验申请明细保存
     * @return
     * @author 陈晓阳
     */
    private int saveLabItem(LabApply labApply,String clincItemId) {
        String[]         ids       = clincItemId.split(",");
        for (String id : ids) {
            String[]       xm             = id.split("-");
            PriceList      priceList      = priceListDao.get(xm[0]);
            String         clinicItemId   = xm[1];
            ClinicVsCharge clinicVsCharge = clinicVsChargeDao.findByClinicIdChargeId(clinicItemId, xm[0]);
            Double         amount         = Double.valueOf(clinicVsCharge.getAmount());
            LabItem        saveData       = new LabItem();
            saveData.setApplyId(labApply.getId());
            saveData.setItemType(xm[2]);
            saveData.setOrgId(labApply.getOrgId());
            saveData.setItemName(priceList.getItemName());
            saveData.setItemCode(priceList.getItemCode());
            saveData.setClinicItemId(xm[1]);
            saveData.setCosts(amount * priceList.getPrice() + "");
            saveData.setPriceId(priceList.getId());
            this.labItemService.save(saveData);
        }
        return ids.length;
    }

    /**
     * 检验申请保存单表
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    private LabApply saveLabApply(LabApply labApply) {
        ClinicMaster clinicMaster=clinicMasterService.get(labApply.getClinicId());
        String testNo="JY"+clinicMaster.getClinicNo()+(int)(Math.random()*9000);
        labApply.setApplyOn(testNo);
        labApply.setInoroutFlag("0");
        labApply.setConfirmFlag("0");
        labApply.setChargeFlag("0");
        //labApply.setBillingDept(UserUtils.getUser().getOrgDept().getId());
        this.save(labApply);
        return labApply;
    }

    /**
     * 删除检验申请主表和子表
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public int deleteLab(String id){
        labItemService.deleteByApplyId(id);
        int i = this.labApplyDao.deleteApply(id);
        return i ;
    }


    /**
     * 根据Id删除检验申请主表数据
     *
     * @param id
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    private int deleteLabApplyById(String id) {
        return this.labApplyDao.deleteLabApplyById(id);
    }


    /**
     * 护士端--未尽检验项目
     *
     * @param visitId
     * @return
     * @author 赵宁
     */
    public List<LabApply> getUnfinishedLab(String visitId) {
        return labApplyDao.getUnfinishedLab(visitId);
    }


    @Transactional(readOnly = false)
    public int inpRetCharge(LabApply labApply) {
        int num = 0;
        String applyId = labApply.getId();
        if ("1".equals(labApply.getChargeFlag())) {
            num = dao.inpOutpRet("5", applyId); // 修改退费状态  3:已退；5申请
        } else {
        }
        return num;

    }


    /**
     * emr接口--查询检验以及检验结果
     * @param baseDto
     * @return
     * @author 赵宁
     */
    public List<BaseDto> findLabByEmr(BaseDto baseDto){
        return dao.findLabByEmr(baseDto);
    }

    public LabApply getApply(String ordersId){
        return labApplyDao.getApply(ordersId);
    }

    public List<LabApply> getByClinicId(String clinicId) {
        return dao.getByClinicId(clinicId);
    }
}